﻿using Silverlight.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Silverlight
{
    public class SelectDatabaseDialogResult
    {
        public List<BackupContracts.Sql.SqlDatabase> Databases { get; set; }
    }

    public partial class SelectDatabaseDialog : ChildWindow
    {
        SelectDatabaseDialogResult result;
        readonly AutoResetEvent waitHandle;

        public static Task<SelectDatabaseDialogResult> ShowModal()
        {
            var dialog = new SelectDatabaseDialog();
            dialog.Show();
            dialog.Closed += (s, e) => dialog.waitHandle.Set();
            return Task<SelectDatabaseDialogResult>.Factory.StartNew(() =>
            {
                dialog.waitHandle.WaitOne(); return dialog.result;
            });
        }

        public SelectDatabaseDialog()
        {
            InitializeComponent();
            waitHandle = new AutoResetEvent(false);
            Loaded += SelectDatabaseDialog_Loaded;
        }

        async void SelectDatabaseDialog_Loaded(object sender, RoutedEventArgs e)
        {
            DataContext = new MainPageViewModel(null);
            await ViewModel.LoadAllServersAsync();
        }

        private MainPageViewModel ViewModel
        {
            get
            {
                return DataContext as MainPageViewModel;
            }
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            result = new SelectDatabaseDialogResult();
            result.Databases = ViewModel.SelectableDatabases.Where((d) => d.Selected).Select((d) => d.Database).ToList();
            Close();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}

